package Chapter2;

public class TermX implements Comparable<TermX>, Addible<TermX>{
    protected int xexp,coef;

    public int getXexp() {
        return this.xexp;
    }

    public void setXexp(int xexp) {
        this.xexp = xexp;
    }

    public int getCoef() {
        return this.coef;
    }

    public void setCoef(int coef) {
        this.coef = coef;
    }

    public TermX(int coef, int xexp) {
        this.coef = coef;
        this.xexp = xexp;
    }

    public TermX(TermX termX) {
        this(termX.coef, termX.xexp);
    }

    public TermX(String termstr) {
        if (termstr.charAt(0) == '+')
            termstr = termstr.substring(1);//去掉‘+’号
        int i = termstr.indexOf('x');
        if (i == -1) {//没有x，指数为0
            this.coef = Integer.parseInt(termstr);
            this.xexp = 0;
        } else if (i == 0) { //x在开头，系数为1
            this.coef = 1;
        } else {
            String str = termstr.substring(0, i); //取x前的系数
            if (str.equals("-"))
                this.coef = -1;
            else
                this.coef = Integer.parseInt(str);
        }
        i = termstr.indexOf('^');
        if (i == -1)
            this.xexp = 1;
        else
            this.xexp=Integer.parseInt(termstr.substring(i+1));
    }


    public String toString() {
        String str = this.coef > 0 ? "+" : "-";
        if (this.xexp == 0 || this.xexp > 0 && this.coef != 1 && this.coef != -1)
            str += Math.abs(this.coef);
        if (this.xexp > 0)
            str += "x";
        if (this.xexp > 1)
            str += "^" + this.xexp;
        return str;
    }

    public int compareTo(TermX termX) {
        return this.xexp == termX.xexp ? 0 : (this.xexp < termX.xexp ? -1 : 1);
    }

    public void add(TermX termX) {
        this.coef+=termX.coef;
    }

    public void minus(TermX termX){
        this.coef-=termX.coef;
    }

    public boolean removable() {
        return this.coef == 0;
    }

    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj instanceof TermX) {
            TermX termX = (TermX) obj;
            return this.coef == termX.coef && this.xexp == termX.xexp;
        }
        return false;
    }
}
